package javango.forms.widgets;

import java.util.LinkedHashMap;
import java.util.Map;

public abstract class AbstractWidget implements Widget {

	private Map<String, Object> attrs;
	
	public AbstractWidget(Map<String, Object> attrs) {
		super();
		this.attrs = attrs == null ? new LinkedHashMap<String, Object>() : attrs;
	}

	/**
	 * Returns this Widget rendered as HTML.  
	 * 
	 * The 'value' given is not guaranteed to be valid input, so subclass
	 * implementations should program defensively.
	 * 
	 * @param name
	 * @param value
	 * @param attrs
	 * @return
	 */
	public abstract String render(String name, Object value, Map<String, Object>  attrs);
	
	public String asText(Object value) {
		return value == null ? "" : value.toString();
	}

	public Map<String, Object> buildAttrs(Map<String, Object> extraAttrs) {
		Map<String, Object> attrs = new LinkedHashMap<String, Object>(this.attrs);
		if (extraAttrs != null) {
			attrs.putAll(extraAttrs);
		}
		return attrs;
	}

	public String[] valueFromMap(Map<String, String[]> map, String name) {
		return map.get(name);
	}
	
	public Map<String, Object> getAttrs() {
		return attrs;
	}

	public void setAttrs(Map<String, Object> attrs) {
		this.attrs = attrs;
	}

}
